package com.phenix.mvp.base.mvp;

import android.support.annotation.NonNull;

import com.phenix.mvp.base.Repository;
import com.phenix.mvp.util.TUtil;

import java.util.Collection;
import java.util.Map;

/**
 * @author  zhouphenix on 2017-1-1.
 */
public class AdapterPresenter<R extends Repository> extends BasePresenter {
    private R mRepository;
    private int page;
    private IAdapterView mIAdapterView;
    private Map<String, Object> mOldParams;

    public AdapterPresenter(@NonNull IAdapterView mIAdapterView) {
        this.mIAdapterView = mIAdapterView;
        onAttach();
    }

    public void setRepository(@NonNull Class<? extends Repository> cls) {
        this.mRepository = TUtil.getInstance(cls);
        mOldParams = mRepository.params;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setParams(@NonNull Map<String, Object> params) {
        mRepository.params = params;
    }

    public void resetParams() {
        mRepository.params = mOldParams;
    }

    public void fetch() {
        addDisposable(mRepository.getPageAt(page).subscribe(data -> {
            mIAdapterView.data((Collection) data, page);
            ++page;
        }, e -> mIAdapterView.error(((Throwable) e).getMessage())));
    }

    public interface IAdapterView {
        void empty();

        void data(Collection data, int page);

        void error(String msg);
    }
}
